package org.shiro.demo.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.shiro.demo.dao.util.QueryCondition;
import org.shiro.demo.entity.GroupInstance;
import org.shiro.demo.entity.GroupOrder;
import org.shiro.demo.entity.OrderProp;
import org.shiro.demo.entity.ResponseResult;
import org.shiro.demo.entity.User;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.IGroupIntanceService;
import org.shiro.demo.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/groupinstance")
public class GroupInstanceController {

	@Resource(name = "groupInstanceService")
	IGroupIntanceService groupInstanceService;

	// @Resource(name = "groupDetailService")
	// IGroupDetailService groupDetailService;

	@Resource(name = "userService")
	IUserService userService;

	@Resource(name = "baseService")
	private IBaseService baseService;

	private User getCurrentUser() {
		Subject currentAdmin = SecurityUtils.getSubject();

		return (User) currentAdmin.getPrincipal();
	}

	/**
	 * 增加团实例。。团长 开团
	 * 
	 * 
	 * 规则，先买单再开团..
	 * 
	 * 如果是微信支付，可以去看查下 是否已经付款。
	 * 
	 * 传递id。。不是uuid
	 * 
	 * @param groupId
	 *            团id
	 * @return
	 */
	@RequestMapping("/add")
	@RequiresAuthentication
	@RequiresRoles("customer")
	@ResponseBody
	public Object add(@RequestParam(value = "groupId", required = true) int groupId, @RequestParam(value = "orderId", required = true) long orderId) {
		ResponseResult rr = new ResponseResult();
		rr.setCode(0);
		try {
			GroupInstance groupInstance = new GroupInstance();

			User captain = getCurrentUser();

			GroupOrder groupOrder = baseService.getById(GroupOrder.class, orderId); // 找到订单
			if (groupOrder == null) {
				rr.setInfo("订单不存在");
				return rr;
			}
			if (groupOrder.getUser().getId() != captain.getId()) {
				rr.setInfo("订单不属于 您");
				return rr;
			}
			if (groupOrder.getOrderProp().getId() != 2L) {
				rr.setInfo("订单未付款");
				// 为了最好的服务。决定使用微信支付，，可以主动去查询
				return rr;
			}

			if (groupOrder.getGroup().getId() != groupId) {
				rr.setInfo("订单团类型有误");
				return rr;
			}

			if (groupOrder.getGroupInstance() != null) {
				rr.setInfo("订单已 绑定 团实例");
				return rr;
			}
			// 过了五道关口，走到下面这一步
			groupInstance.setCaptain(captain);

			// 船长被加入到成员中去了

			Set<GroupOrder> orders = new HashSet<GroupOrder>();
			orders.add(groupOrder);

			groupInstance.setOrders(orders);// 设置 order 。

			GroupInstance newGroupInstance = (GroupInstance) groupInstanceService.saveNow(groupInstance);// 保存。。得到id
			rr.setCode(1);
			rr.setInfo("success");
			rr.setObject(newGroupInstance);// 返回object。带着id，可以分享
			return rr;
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			rr.setInfo("内部执行出错");
			return rr;
		}

	}

	/**
	 * 更新团实例。。团员参团
	 * 
	 * 
	 * 规则，先买单再参团..
	 * 
	 * 可能会出现 超员现象。没问题。
	 * 
	 * 传递id。。不是uuid
	 * 
	 * @param groupInstanceId
	 *            团实例id
	 * @return
	 */
	@RequestMapping("/attend")
	@RequiresAuthentication
	@RequiresRoles("customer")
	@ResponseBody
	public Object attend(@RequestParam(value = "groupinstanceId", required = true) long groupInstanceId, @RequestParam(value = "orderId", required = true) long orderId) {
		ResponseResult rr = new ResponseResult();
		rr.setCode(0);
		rr.setObject("");
		try {
			GroupInstance groupInstance = baseService.getById(GroupInstance.class, groupInstanceId);

			User captain = getCurrentUser();

			GroupOrder groupOrder = baseService.getById(GroupOrder.class, orderId); // 找到订单
			if (groupOrder == null) {
				rr.setInfo("订单不存在");
				return rr;
			}
			if (groupOrder.getUser().getId() != captain.getId()) {
				rr.setInfo("订单不属于 您");
				return rr;
			}
			if (groupOrder.getOrderProp().getId() != 2L) {
				rr.setInfo("订单未付款");
				return rr;
			}

			if (groupOrder.getGroup().getId() != groupInstance.getId()) {
				rr.setInfo("订单团类型有误");
				return rr;
			}

			if (groupOrder.getGroupInstance() != null) {
				rr.setInfo("订单已 绑定 团实例");
				return rr;
			}
			// 过了五道关口，走到下面这一步

			// 不需要团长
			// groupInstance.setCaptain(captain);

			// 订单 被加入到成员中去了
			Set<GroupOrder> orders = groupInstance.getOrders();
			// 不做限制

			// if (orders.size() >= groupOrder.getGroup().getPersonAmount()) {
			// rr.setInfo("团已满员");
			// return rr;
			// }
			// 增加 团员
			orders.add(groupOrder);
			groupInstance.setOrders(orders);// 设置 order 。

			groupInstanceService.update(groupInstance);// 保存
			rr.setCode(1);
			rr.setInfo("success");
			rr.setObject("");
			return rr;
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			rr.setInfo("内部执行出错");
			return rr;
		}

	}

	/**
	 * 
	 * 查团实例.. 不需要登陆
	 * 
	 * @param groupinstanceId
	 *            团实例id
	 * @return
	 */
	@RequestMapping("/check")
	@ResponseBody
	public Object check(@RequestParam(value = "groupinstanceId", required = true) long groupinstanceId) {
		ResponseResult rr = new ResponseResult();
		GroupInstance groupInstance = baseService.getById(GroupInstance.class, groupinstanceId);
		if (groupInstance == null) {
			rr.setCode(0);
			rr.setInfo("团不存在");
			return rr;
		}
		rr.setCode(1);
		rr.setObject(groupInstance);
		return rr;
	}

	/**
	 * 
	 * 根据团实例得到 所有参与人.. 公开的。不用登陆
	 * 
	 * @param groupinstanceId
	 *            团实例id
	 * @return
	 */
	@RequestMapping("/get")
	@ResponseBody
	public Object get(@RequestParam(value = "groupinstanceId", required = true) long groupinstanceId) {
		ResponseResult rr = new ResponseResult();
		GroupInstance groupInstance = baseService.getById(GroupInstance.class, groupinstanceId);
		if (groupInstance == null) {
			rr.setCode(0);
			rr.setInfo("团不存在");
			return rr;
		}
		rr.setCode(1);
		List<QueryCondition> lists = new ArrayList<QueryCondition>();
		lists.add(new QueryCondition("groupInstance", QueryCondition.EQ, groupInstance));
		// 要求订单是支付的。
		OrderProp orderProp = new OrderProp();
		orderProp.setId(2L);
		
		OrderProp orderProp3L = new OrderProp();
		orderProp3L.setId(3L);
		List<OrderProp> props = new ArrayList<OrderProp>();
		props.add(orderProp3L);
		props.add(orderProp);
		
		lists.add(new QueryCondition("orderProp", QueryCondition.IN, props));
		List<GroupOrder> orders = baseService.get(GroupOrder.class, lists);
		List<User> users = new ArrayList<User>();
		for (GroupOrder order : orders) {
			User user = order.getUser();
			user.setCreateTime(order.getPostTime());
			users.add(user);
		}
		rr.setObject(users);
		rr.setInfo("success");
		return rr;
	}
}
